//
//  ViewController.m
//  LC_RichTextFiled
//
//  Created by 上海雷默广告有限公司 on 2017/3/22.
//  Copyright © 2017年 liCheng. All rights reserved.
//

#import "ViewController.h"
#import "UIControl+Category.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,strong)NSMutableDictionary *mutImgDict;
@property(nonatomic,strong)NSMutableArray *mutImgArray;
@property(nonatomic,strong)NSMutableArray *imgArray;//最终确定照片URl数组


@property (nonatomic, strong) UIButton *buttonOfCancel;
@property (nonatomic, strong) NSMutableAttributedString *attriStr;
@property (nonatomic, strong) NSAttributedString* imageAttachment;
@property (nonatomic, assign) CGFloat myFlag;

@property (nonatomic, strong) NSMutableArray *mArrayOfHeight;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.myFlag = 0;
    self.mArrayOfHeight = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 点击添加图片的方法
- (IBAction)addPicAction:(id)sender {
    UIImagePickerController *imgPicker = [UIImagePickerController new];
    imgPicker.delegate = self;
    imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imgPicker animated:YES completion:nil];
}

#pragma mark - 生成文本  包含了图片地址链接  可以直接传给后台制作HTML页面
- (IBAction)overAction:(id)sender {
    NSLog(@"_textView.attributedText -- :%@", _textView.attributedText);
    NSString *textStr = [[self textStringWithSymbol:@"[图片]" attributeString:_textView.attributedText] mutableCopy];
    int index = 0;
    //通过替换
    for (int i = 0; i <= textStr.length - 4; i ++) {
        NSString *tempStr = [textStr substringWithRange:NSMakeRange(i, 4)];
        NSLog(@"tempStr -- %@", tempStr);
        if ([tempStr isEqualToString:@"[图片]"]) {
            NSString *imgStr = [NSString stringWithFormat:@"<img src = '%@'/>",self.imgArray[index]];
            textStr = [textStr stringByReplacingCharactersInRange:NSMakeRange(i, 4) withString:imgStr];
            index ++;
        }
    }
    NSLog(@"textStr -- %@", textStr);
}

#pragma mark - UIImagePickerControllerDelegate (图片打开方法)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self dismissViewControllerAnimated:YES completion:^{
        self.myFlag ++;
        // 获取选择的图片
        UIImage * img = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self uploadPicture:img];
        // 创建文本附件类
        NSTextAttachment* textAttachment = [[NSTextAttachment alloc] init];
        textAttachment.image = img;
        textAttachment.bounds = CGRectMake(0, 0, self.view.frame.size.width, [self getImgHeightWithImg:img]);
        // 给属性字符串添加文本附件
        self.imageAttachment = [NSAttributedString attributedStringWithAttachment:textAttachment];
        self.attriStr = [_textView.attributedText mutableCopy];
        [self.attriStr appendAttributedString:_imageAttachment];
        _textView.attributedText = self.attriStr;
        // 创建删除图片的 button
        UIButton *buttonOfDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        [_textView addSubview:buttonOfDelete];
        buttonOfDelete.frame = CGRectMake(20, _textView.contentSize.height - [self getImgHeightWithImg:img], 20, 20);
        NSLog(@"%f--%f--%f--%f", buttonOfDelete.frame.origin.x, _buttonOfCancel.frame.origin.y, _buttonOfCancel.frame.size.width, _buttonOfCancel.frame.size.height);
        [self.mArrayOfHeight addObject:[NSString stringWithFormat:@"%f", _buttonOfCancel.frame.size.height]];
        buttonOfDelete.backgroundColor = [UIColor redColor];
        [buttonOfDelete addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        buttonOfDelete.tag = self.attriStr.length - 1 + 100;
        [buttonOfDelete setOrderTags:[NSString stringWithFormat:@"%f", self.myFlag]];
    }];
}

#pragma mark - button 点击事件
- (void)buttonAction:(UIButton *)button {
    // 重新给 _textView attributedText 属性赋值
    [self.attriStr deleteCharactersInRange:NSMakeRange(button.tag - 100, 1)];
    _textView.attributedText = self.attriStr;
    // 做一个判断, 删的图片上面是不是还有图片
//    UIButton *button = [_textView viewWithTag:button];
//    if (UIButton *button)
    NSLog(@"--- button tagtwo -- %@", button.OrderTags);
    // 移除掉 button
    [button removeFromSuperview];
    
    
    
}

#pragma mark - //取消回调
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{
        [_textView becomeFirstResponder];
    }];
}

#pragma mark - //上传照片
- (void)uploadPicture:(UIImage *)image {
    //此处是上传单张图片   ------ 等上传成功后按照下面去存储数据
    /*
            NSDictionary *rawDic = (NSDictionary *)responseObject;
            NSDictionary *infoDic = [rawDic objectForKey:@"info"];
            
            NSString *url = [infoDic valueForKey:@"url"];
            [self.mutImgDict setValue:image forKey:url];
            [self.textView becomeFirstResponder];
    */
}

#pragma mark - //根据屏幕宽度适配高度
- (CGFloat)getImgHeightWithImg:(UIImage *)img {
    CGFloat height = ((self.view.frame.size.width)/ img.size.width) * img.size.height;
    return height;
}

#pragma mark - 富文本转换操作 /** 将富文本转换为带有图片标志的纯文本*/
- (NSString *)textStringWithSymbol:(NSString *)symbol attributeString:(NSAttributedString *)attributeString{
    NSString *string = attributeString.string;
    NSLog(@"attributeString.string -- %@", attributeString.string);
    string = [self stringDeleteString:@"\n" frontString:@"[图片]" inString:string];
    NSLog(@"stringstringstringstring:%@", string);
    //最终纯文本
    NSMutableString *textString = [NSMutableString stringWithString:string];
    //替换下标的偏移量
    __block NSUInteger base = 0;
    
    //遍历
    [attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length)
                                options:0
                             usingBlock:^(id value, NSRange range, BOOL *stop) {
                                 //检查类型是否是自定义NSTextAttachment类
                                 if (value && [value isKindOfClass:[NSTextAttachment class]]) {
                                     //替换
                                     [textString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:symbol];
                                     //增加偏移量
                                     base += (symbol.length - 1);
                                     //将富文本中最终确认的照片取出来
                                     NSTextAttachment *attachmentImg = (NSTextAttachment *)value;
                                     [self.mutImgArray addObject:attachmentImg.image];
                                 }
                             }];
    //-------------- 最后点击完成事件时 通过对比将富文本中最终确定的照片审选出来 找到对应照片的URl地址
    NSArray *keyArray = [self.mutImgDict allKeys];
    
    for (int i = 0; i < _mutImgArray.count; i ++) {
        UIImage *img = _mutImgArray[i];
        for (int j = 0; j < keyArray.count; j ++) {
            UIImage *myImg = [self.mutImgDict valueForKey:keyArray[j]];
            if (myImg == img) {
                [self.imgArray addObject:keyArray[j]];
            }
        }
    }
    //--------------
    NSLog(@"%ld", self.imgArray.count);
    return textString;
}

#pragma mark - /** 删除字符串*/
- (NSString *)stringDeleteString:(NSString *)deleteString frontString:(NSString *)frontString inString:(NSString *)inString{
    NSArray *ranges = [self rangeOfSymbolString:frontString inString:inString];
    NSMutableString *mutableString = [inString mutableCopy];
    NSUInteger base = 0;
    for (NSString *rangeString in ranges) {
        NSRange range = NSRangeFromString(rangeString);
        [mutableString deleteCharactersInRange:NSMakeRange(range.location - deleteString.length + base, deleteString.length)];
        base -= deleteString.length;
    }
    return [mutableString copy];
}

#pragma mark - /** 统计文本中所有图片资源标志的range*/
- (NSArray *)rangeOfSymbolString:(NSString *)symbol inString:(NSString *)string {
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString *string1 = [string stringByAppendingString:symbol];
    NSString *temp;
    for (int i = 0; i < string.length; i ++) {
        temp = [string1 substringWithRange:NSMakeRange(i, symbol.length)];
        if ([temp isEqualToString:symbol]) {
            NSRange range = {i, symbol.length};
            [rangeArray addObject:NSStringFromRange(range)];
        }
    }
    return rangeArray;
}

#pragma mark - 懒加载
- (NSMutableArray *)mutImgArray
{
    if (!_mutImgArray) {
        _mutImgArray = [NSMutableArray array];
    }
    return _mutImgArray;
}
- (NSMutableDictionary *)mutImgDict
{
    if (!_mutImgDict) {
        _mutImgDict = [NSMutableDictionary dictionary];
    }
    return _mutImgDict;
}
-(NSMutableArray *)imgArray
{
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}

@end
